package com.lyy.king.gateway.filter;

import com.lyy.king.common.core.constant.TokenConstants;
import com.lyy.king.common.utils.utils.StringUtils;
import com.lyy.king.gateway.client.AuthClient;
import com.lyy.king.gateway.utils.GeneralResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

/**
 * @BelongsProject: springcloud-learning
 * @BelongsPackage: com.cdx.gateway.filter
 * @Author: cdx
 * @CreateTime: 2022-06-04  17:15
 * @Description: 身份登录过滤器
 * @Version: 1.0
 */
@Component
public class LoginGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private AuthClient authClient;
    // TODO ,访问白名单，后续加入配置，暂时先写死登录路径
    private static List<String> fileUrlList = new ArrayList<>();

    static {
        fileUrlList.add("/system/login");
        fileUrlList.add("/tools/captchaImage");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求体对象
        ServerHttpRequest request = exchange.getRequest();
        // 获取访问的路径
        String path = request.getURI().getPath();
        // 如果访问的路径在白名单，放行
        if (StringUtils.matches(path, fileUrlList)) {
            // 放行，TODO 准备使用 dubbo进行改造
            return chain.filter(exchange);
        }
        // 获取token
        String token = getToken(request);

        // 判断是否有token参数携带
        if (StringUtils.isBlank(token) && !authClient.checkToken(token)) {
            // 如果没有携带token或者token校验失败。则返回401状态码
            return GeneralResponseUtils.returnErrorResponse(exchange, HttpStatus.UNAUTHORIZED.value(), "请登录").setComplete();
        }
        // 放行
        return chain.filter(exchange);
    }

    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(TokenConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX)) {
            token = token.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY);
        }
        return token;
    }

    /**
     * 执行优先级，数字越小，越靠前
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}